<?php

require_once(dirname(__FILE__) . '/appconf.php');

class Product extends Site {

    function setup() {
        $this->run_modes('invite_list', 'submitReport_list', 'submit_application', 'invite_inpage', 'report_inpage', 'detail', 'reportDetail', 'readReport_list', 'report_show', 'report_add', 'ajax', 'test_report', 'approveReport', 'emailApplication');
        $this->start_mode('invite_list');
        $this->selfurl = 'product.php';
        $this->pagesize = 5;
        parent::setup();
        include("common.php");
    }

    function cgiapp_prerun($rm = '') {
        $this->dbMove = getModel('Model_dbMove');
        $this->Product = getModel('Model_Product');
        $this->Product_application = getModel('Model_ProductApplication');
        $this->Lookup = getModel('Model_Lookup');
        $this->ProductReports = getModel('Model_ProductReports');
        $this->ProductReportsComment = getModel('Model_ProductReportsComment');
        $this->MemberLike = getModel('Model_MemberLike');
        $this->ModelMember = getModel('Model_Member');
        $this->member = $this->s_param('memberData');

        parent::cgiapp_prerun();
    }

    function action_invite_list() {

        $order = $this->get_q('order', 1, 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_invite_list_expert.php' : 'p_invite_list_general.php';

        // <!--邀請數據列表
        switch ($order) {
            case 2:
                $orderby = "TB1.report_starttime asc,TB1.id desc";
                break;
            case 3:
                $orderby = "TB1.click desc,TB1.id desc";
                break;
            case 1:
            default:
                $orderby = "TB1.apply_starttime desc,TB1.id desc";
                break;
        }
        $data = $this->Product->getProductList($mtype, 1, $orderby, 0, 0);

        $res = isset($data['result']) && !empty($data['result']) ? $data['result'] : array();
        foreach ($res as $k => $v) {
            $res[$k]['_difTime'] = explode(" ", str_diff_time($v['report_starttime']));
            $_data = $this->Product->getProductById($v['id']);
            $res[$k]['capacity'] = $_data['capacity_trial'];
            $res[$k]['_photo_url'] = PhotoResize($v['cover'], 158, 107);
            //$res[$k]['name'] = wordscut($res[$k]['name'],15);
            //立即申請 bt 待續
        }


        // <!-- 已錯過的邀請列表
        $orderby1 = 'TB1.report_starttime desc,TB1.id desc';
        $data1 = $this->Product->getProductList($mtype, 3, $orderby1, 1, 16);
        $res1 = isset($data1['result']) && !empty($data1['result']) ? $data1['result'] : array();
        foreach ($res1 as $k => $v) {
            $res1[$k]['_photo_url'] = PhotoResize($v['cover'], 158, 107);
            $res1[$k]['name'] = wordscut($v['name'], 8);
            $res1[$k]['cname'] = wordscut($v['cname'], 8);
        }

        //echo '<pre>'.var_export($res,1).'</pre>';
        $this->tmpl_assign('result', $res);
        $this->tmpl_assign('result1', $res1);
        $this->tmpl_assign('order', $order);
        $this->tmpl_assign('mtype', $mtype);
        return $this->load_tmpl($tmpl);
    }

    function action_submitReport_list() {
        $mtype = $this->get_q('mtype', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_submitReport_list_expert.php' : 'p_submitReport_list_general.php';

        $orderby = 'TB1.report_starttime desc,TB1.id desc';
        $data = $this->Product->getProductList($mtype, 2, $orderby, 0, 0);

        $res = isset($data['result']) && !empty($data['result']) ? $data['result'] : array();
        foreach ($res as $k => $v) {
            $res[$k]['name'] = wordscut($v['name'], 13);
            $res[$k]['cname'] = wordscut($v['cname'], 13);
            $res[$k]['_photo_url'] = PhotoResize($v['cover'], 111, 102);
            $res[$k]['_rep_count'] = db_query_count('product_reports', 'status=1 and oid=' . $v['id']);
        }

        //echo '<pre>'.var_export($res,1).'</pre>';
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('result', $res);
        return $this->load_tmpl($tmpl);
    }

    function action_submit_application() {
        $pid = $this->get_q('pid', 1, 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_submit_application_expert.php' : 'p_submit_application_general.php';
        if ($this->get_q('issubmit') == 'true') {

            if (empty($this->member)) {
                $this->iframeReturn(null, 'callback', array('retcode' => 9, 'msg' => NO_LOGIN));
            }
            $_c = db_query_count('product_application', "oid=" . $pid . " and mid=" . $this->member['id']);
            if ($_c > 0) {
                $this->iframeReturn(null, 'callback', array('retcode' => 9, 'msg' => HAS_APPLY));
            }


            $attr = $mjson = $param = array();
            $attr['oid'] = $pid;
            $attr['mid'] = $this->member['id'];
            $attr['application_status'] = 1;
            $attr['status'] = 1;
            $attr['body'] = htmlspecialchars($this->get_q('reason', ''));
            if (empty($attr['body'])) {
                $this->iframeReturn(null, 'callback', array('retcode' => 1, 'msg' => HAS_INVITE_REASON));
            }

            $mjson['itrial_url'] = htmlspecialchars($this->get_q('itrial_url', ''));
            if (empty($mjson['itrial_url'])) {
                $this->iframeReturn(null, 'callback', array('retcode' => 2, 'msg' => HAS_REPORT_URL));
            }

            $mjson['www_url2'] = htmlspecialchars($this->get_q('www_url2', ''));
            if (empty($mjson['www_url2'])) {
                $this->iframeReturn(null, 'callback', array('retcode' => 3, 'msg' => HAS_REPORT_URL));
            }

            $mjson['photo'] = $this->get_q('photo_path', '');
            if (empty($mjson['photo'])) {
                $this->iframeReturn(null, 'callback', array('retcode' => 4, 'msg' => HAS_INVITE_PIC));
            }

            $ques = $this->get_q('ques');
            foreach ($ques as $k => $v) {
                $mjson['ques_' . $k] = htmlspecialchars($v);
                if (empty($mjson['ques_' . $k])) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 5, 'c' => $k, 'msg' => HAS_REPORT_QUESTION));
                }
            }

            $isread = $this->get_q('isread', 0, 'int');
            if (empty($isread)) {
                $this->iframeReturn(null, 'callback', array('retcode' => 7, 'msg' => HAS_AGREE_TERMS));
            }

            if ($this->get_q('facebook')) {

                $facebookarr = array();
                $facebook = $this->ModelMember->getMemberFacebook($this->member['id']);
                if ($facebook['result'])
                    $facebookarr = $facebook['result'][0];
                if (!$facebookarr['accesstoken']) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 8, 'msg' => NO_LOGIN_FB));
                } else {

                    require_once(LIB_PATH . '/Vendor/Facebook/sdk/facebook.php');
                    require_once(LIB_PATH . '/Vendor/Facebook/FaceBookApi.class.php');

                    $fb_config = array();
                    $fb_config['appId'] = FB_APPID;
                    $fb_config['secret'] = FB_SECRET;
                    $fb_config['scope'] = FB_SCOPE;
                    $fb_config['cookie'] = FB_COOKIE;
                    $fb_config['fileUpload'] = FB_FILEUPLOAD_SUPPORT;

                    $data = $this->Product->getProductById($pid);
                    global $site_global_config;
                    $global_url = $site_global_config['URL'];

                    $params = array(
                        'name' => $data['cname'] . '申請試用',
                        'link' => $global_url . "product.php?action=submit_application&mtype=" . $mtype . "&pid=" . $pid,
                        'description' => $attr['body'],
                        'picture' => $global_url . PhotoResize($data['cover'], 158, 107),
                    );

                    $facebook = new FaceBookApi($fb_config);
                    $result = $facebook->postToWall($facebookarr['fb_id'], $facebookarr['accesstoken'], $params);
                }
            }

            $attr['message_json'] = json_encode($mjson);

            $res = db_add('product_application', $attr);
            if ($res) {
                $_data = db_query_one('product', array('field' => 'apply_num', 'where' => 'id=' . $attr['oid']));
                $apply_num = intval($_data['result']['apply_num']) + 1;
                db_update('product', array('apply_num' => $apply_num), ' id=' . $attr['oid']);
                $this->iframeReturn(null, 'callback', array('retcode' => 10, 'msg' => 'success'));
            }
        } else {
            $data = $this->Product->getProductById($pid);
            $data['_photo_url'] = PhotoResize($data['cover'], 158, 107);

            /* $arr = array();
              $arr[0]['q'] = '產品申請問題1 test？？？';//問題
              $arr[0]['t'] = 1;//問題類型
              $arr[1]['q'] = '產品申請問題2 test？？？';
              $arr[1]['t'] = 1;
              $arr[2]['q'] = '產品申請問題3 test？？？';
              $arr[2]['t'] = 1;
              echo json_encode($arr); */
            $data['questions'] = json_decode($data['questions_json'], 1);

            $this->tmpl_assign('pid', $pid);
            $this->tmpl_assign('result', $data);
            $this->tmpl_assign('mtype', $mtype);
            $this->tmpl_assign('selfurl', $this->selfurl);
            $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
            $this->tmpl_assign('pageValue', $pageValue);

            return $this->load_tmpl($tmpl);
        }
    }

    function action_invite_inpage() {

        $pid = $this->get_q('pid', 1, 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        $page = $this->get_q('page', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_invite_inpage_expert.php' : 'p_invite_inpage_general.php';
        $data = $this->Product->getProductById($pid);

        $_c_res = db_update('product', array('click' => (intval($data['click']) + 1)), 'id=' . $pid);
        $data['click'] = $_c_res > 0 ? intval($data['click']) + 1 : $data['click'];



        $data['_difTime'] = explode(" ", str_diff_time($data['report_starttime']));
        $data['_photo_url'] = PhotoResize($data['cover'], 158, 107);

        $data1 = $this->Product_application->getAllUser($pid);
        $userlist = isset($data1['result']) && !empty($data1['result']) ? $data1['result'] : array();
        foreach ($userlist as $k => $v) {
            $userlist[$k]['photo_l'] = PhotoResize($v['photo'], 56, 56);
        }
        $data2 = $this->Product_application->getApplicationList($pid, 0, "id desc", $page, $this->pagesize);
        $reportlist = isset($data2['result']) && !empty($data2['result']) ? $data2['result'] : array();
        foreach ($reportlist as $k => $v) {
            $reportlist[$k]['photo_l'] = PhotoResize($v['photo'], 56, 56);
        }

        //echo '<pre>'.var_export($data2,1).'</pre>';

        $pagelist = showPage($data2['pageinfo']['total'], $this->pagesize, $page, 'product.php?action=invite_inpage&mtype=' . $mtype . '&pid=' . $pid);


        //是否隱藏已申請會員及三部曲部份
        $turnpage = $page > 1 ? 1 : 0;

        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('turnpage', $turnpage);
        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('data', $data);
        $this->tmpl_assign('userlist', $userlist);
        $this->tmpl_assign('reportlist', $reportlist);
        $this->tmpl_assign('NO_USERNAME', NO_USERNAME);
        $this->tmpl_assign('NO_PASSWORD', NO_PASSWORD);
        $this->tmpl_assign('ERR_CAPTCHA', ERR_CAPTCHA);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
        $this->tmpl_assign('pageValue', $pageValue);
        $memberData = $this->s_param('memberData');
        $this->tmpl_assign('memberData', $memberData);
        global $site_global_config;
        $global_url = $site_global_config['URL'];
        $this->tmpl_assign('global_url', $global_url);

        return $this->load_tmpl($tmpl);
    }

    function action_report_inpage() {
        $pid = $this->get_q('pid', 1, 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        $page = $this->get_q('page', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_report_inpage_expert.php' : 'p_report_inpage_general.php';
        $data = $this->Product->getProductById($pid);

        //人氣自增1
        if (empty($_COOKIE["click_up_one"])) {
            $_c_res = db_update('product', array('click' => (intval($data['click']) + 1)), 'id=' . $pid);
            $data['click'] = $_c_res > 0 ? intval($data['click']) + 1 : $data['click'];
            setcookie("click_up_one", 1, time() + 1);
        }
        //時間
        $data['_difTime'] = explode(" ", str_diff_time($data['report_endtime']));

        $data1_1 = $this->Product_application->getAllUser($pid, 2);
        $data1_2 = $this->Product_application->getAllUser($pid, 1);
        $userlist1 = isset($data1_1['result']) && !empty($data1_1['result']) ? $data1_1['result'] : array();
        $userlist2 = isset($data1_2['result']) && !empty($data1_2['result']) ? $data1_2['result'] : array();
        foreach ($userlist1 as $k => $v) {
            $userlist1[$k]['photo_l'] = PhotoResize($v['photo'], 56, 56);
        }
        foreach ($userlist2 as $k => $v) {
            $userlist2[$k]['photo_l'] = PhotoResize($v['photo'], 56, 56);
        }
        $data2 = $this->Product_application->getApplicationList($pid, 0, "id desc", $page, $this->pagesize);
        $reportlist = isset($data2['result']) && !empty($data2['result']) ? $data2['result'] : array();
        foreach ($reportlist as $k => $v) {
            $reportlist[$k]['photo_l'] = PhotoResize($v['photo'], 56, 56);
        }
        $pagelist = showPage($data2['pageinfo']['total'], $this->pagesize, $page, 'product.php?action=report_inpage&mtype=' . $mtype . '&pid=' . $pid);
        $data['_photo_url'] = PhotoResize($data['cover'], 158, 107);

        //是否隱藏已申請會員及三部曲部份
        $turnpage = $page > 1 ? 1 : 0;

        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('turnpage', $turnpage);
        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('selfurl', $this->selfurl);
        $this->tmpl_assign('data', $data);
        $this->tmpl_assign('userlist1', $userlist1);
        $this->tmpl_assign('userlist2', $userlist2);
        $this->tmpl_assign('reportlist', $reportlist);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));

        $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
        $this->tmpl_assign('pageValue', $pageValue);
        return $this->load_tmpl($tmpl);
    }

    function action_detail() {
        $pid = $this->get_q('pid', 1, 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        $page = $this->get_q('page', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_detail_expert.php' : 'p_detail_general.php';
        $data = $this->Product->getProductById($pid);

        //人氣自增1
        
            $_c_res = db_update('product', array('click' => (intval($data['click']) + 1)), 'id=' . $pid);
            $data['click'] = $_c_res > 0 ? intval($data['click']) + 1 : $data['click'];
            setcookie("click_up_one", 1, time() + 1);
        
        //體驗天數
        $data['_diff_day'] = (int) ((strtotime($data['report_endtime']) - strtotime($data['apply_starttime'])) / 86400);

        //圖片url
        $data['_photo_url'] = PhotoResize($data['cover'], 118, 118);
        //評分
        if (!empty($data['product_reports_stat']['category_score_num'])) {
            $data['_overall'] = round($data['product_reports_stat']['good'] / $data['product_reports_stat']['category_score_num'] * 100);
        } else {
            $data['_overall'] = 0;
        }
        //right 產品屬性info
        $attr = array();
        if (!empty($data['price_trial'])) {
            $data['_attr']['價格'] = '$' . $data['price_trial'];
        }
        if (!empty($data['capacity_trial'])) {
            $data['_attr']['容量'] = $data['capacity_trial'];
        }
        for ($i = 1; $i < 9; $i++) {
            if (!empty($data['attribute_value' . $i])) {
                $data['_attr'][$data['attribute_label' . $i]] = $data['attribute_value' . $i];
            }
        }
        if (!empty($data['about_txt'])) {
            $data['_attr']['相關資料'] = $data['about_txt'];
        }

        //產品好評度 餅圖url

        $_num1 = empty($data['product_reports_stat']['well_score_num1']) ? 0 : intval($data['product_reports_stat']['well_score_num1']);
        $_num2 = empty($data['product_reports_stat']['well_score_num1']) ? 0 : intval($data['product_reports_stat']['well_score_num2']);
        $_num3 = empty($data['product_reports_stat']['well_score_num1']) ? 0 : intval($data['product_reports_stat']['well_score_num3']);
        $_num4 = empty($data['product_reports_stat']['well_score_num1']) ? 0 : intval($data['product_reports_stat']['well_score_num4']);
        $_num5 = empty($data['product_reports_stat']['well_score_num1']) ? 0 : intval($data['product_reports_stat']['well_score_num5']);
        $_img_color = $mtype == 5 ? 1 : 2;
        $pie_datas = array(
            'datas' => array($_num1, $_num2, $_num3, $_num4, $_num5),
            'colorType' => $_img_color
        );
        $data['_pie_url'] = getImgUrl($pie_datas);
        //好評度（很好、好、一般、差、很差）
        $data2 = $this->Lookup->getLookup('product_reports_well');
        $data['_well_score'] = $data2['result'];
        if (!empty($data['product_reports_stat']['category_score_num']) && $data['product_reports_stat']['category_score_num'] > 0) {
            for ($i = 1; $i < 6; $i++) {
                $data['_well_score']['num' . $i] = round($data['product_reports_stat']['well_score_num' . $i] / $data['product_reports_stat']['category_score_num'] * 100) . '%';
            }
        } else {
            $data['_well_score']['num1'] = $data['_well_score']['num2'] = $data['_well_score']['num3'] = $data['_well_score']['num4'] = $data['_well_score']['num5'] = '0%';
        }

        //產品評分、年齡分佈
        $_vote_sum = 0;
        $data1 = $this->Lookup->getLookup('agegroup');
        for ($i = 1; $i < 9; $i++) {
            $_vote_num_temp = empty($data['product_reports_stat']['category_score' . $i]) ? 0 : intval($data['product_reports_stat']['category_score' . $i]);
            $_vote_sum += $_vote_num_temp;
        }
        for ($i = 1; $i < 9; $i++) {
            if (isset($data['vote_option_data']['result'][$i - 1]) && !empty($data['vote_option_data']['result'][$i - 1])) {
                $data['_vote_opt'][$data['vote_option_data']['result'][$i - 1]['cname']] = $_vote_sum > 0 ? round($data['product_reports_stat']['category_score' . $i] / $_vote_sum * 100) . '%' : '0%';
            }
            if (isset($data1['result'][$i - 1]) && !empty($data1['result'][$i - 1])) {
                $data['_age_group'][$data1['result'][$i - 1]['cname']] = !empty($data['product_reports_stat']['category_score_num']) && !empty($data['product_reports_stat']['well_score_num' . $i]) ? round($data['product_reports_stat']['well_score_num' . $i] / $data['product_reports_stat']['category_score_num'] * 100) . '%' : '0%';
            }
        }

        //獲得報告列表資料
        $order = $this->get_q('order', 1, 'int');
        switch ($order) {
            case 2:
                $orderby = "TB1.likes desc";
                break;
            case 1:
            default:
                $orderby = "TB1.addtime desc";
                break;
        }
        $data3 = $this->ProductReports->getReportsList($pid, 0, 0, $orderby, $page, $this->pagesize);
        $data4 = $this->Lookup->getLookup('body_skin'); //膚質
        if (!empty($data3['result'])) {
            foreach ($data3['result'] as $k => $v) {
                $data3['result'][$k]['photo_l'] = PhotoResize($v['photo'], 77, 77);
                $data3['result'][$k]['body'] = wordscut($v['body'], 100);
                $data3['result'][$k]['comments'] = db_query_count('product_reports_comment', "oid=" . $v['id'] . " and status=1");

                //用戶報告圖文
                if (!empty($v['content_json'])) {
                    $data3['_content'][$k] = json_decode($v['content_json'], true);
                    foreach ($data3['_content'][$k] as $k1 => $v1) {
                        if (!empty($data3['_content'][$k][$k1]['p'])) {
                            $data3['_content'][$k][$k1]['p1'] = PhotoResize($v1['p'], 163, 102);
                        }
                    }
                }

                //用戶滿意度
                $j = 0;
                for ($i = 1; $i < 9; $i++) {
                    if (isset($data['vote_option_data']['result'][$i - 1]) && !empty($data['vote_option_data']['result'][$i - 1])) {
                        $data3['_category_score'][$k][$j]['k'] = $data3['result'][$k]['category_score' . $i];
                        $data3['_category_score'][$k][$j]['v'] = $data['vote_option_data']['result'][$i - 1]['cname'];
                        $j++;
                    }
                }

                //是否已關注該用戶
                if (!empty($this->member)) {
                    $_islike = $this->MemberLike->getMemberLike($this->member['id'], 'member', $v['mid']);
                } else {
                    $_islike = 0;
                }
                $data3['result'][$k]['islike'] = !empty($_islike) ? 1 : 0;
            }
        }

        //fb likes
        $data['_fb_likes'] = db_query_count('member_good', "section='product' and sid=" . $pid);

        $pagelist = showPage($data3['pageinfo']['total'], $this->pagesize, $page, 'product.php?action=detail&mtype=' . $mtype . '&pid=' . $pid . '&order=' . $order, 0);

        //echo '<pre>'.var_export($data3,1).'</pre>';

        $this->tmpl_assign('selfurl', $this->selfurl);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('data', $data);
        $this->tmpl_assign('data1', $data1);
        $this->tmpl_assign('data2', $data2);
        $this->tmpl_assign('data3', $data3);
        $this->tmpl_assign('data4', $data4);
        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
        $this->tmpl_assign('pageValue', $pageValue);
        return $this->load_tmpl($tmpl);
    }

    function action_reportDetail() {
        $pure = $this->get_q('pure', 0, 'int'); //是否純淨模式顯示報告，隱藏推薦留言等
        $pid = $this->get_q('pid', 1, 'int');
        $rid = $this->get_q('rid', 0, 'int');
        $page = $this->get_q('page', '1', 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_reportDetail_expert.php' : 'p_reportDetail_general.php';
        $data = $this->Product->getProductById($pid);

        //體驗天數
        $data['_diff_day'] = (int) ((strtotime($data['report_endtime']) - strtotime($data['apply_starttime'])) / 86400);

        //圖片url
        $data['_photo_url'] = PhotoResize($data['cover'], 118, 118);
        //評分
        if (!empty($data['product_reports_stat']['category_score_num'])) {
            $data['_overall'] = round($data['product_reports_stat']['good'] / $data['product_reports_stat']['category_score_num'] * 100);
        } else {
            $data['_overall'] = 0;
        }
        //right 產品屬性info
        $attr = array();
        if (!empty($data['price_trial'])) {
            $data['_attr']['價格'] = '$' . $data['price_trial'];
        }
        if (!empty($data['capacity_trial'])) {
            $data['_attr']['容量'] = $data['capacity_trial'];
        }
        for ($i = 1; $i < 9; $i++) {
            if (!empty($data['attribute_value' . $i])) {
                $data['_attr'][$data['attribute_label' . $i]] = $data['attribute_value' . $i];
            }
        }
        if (!empty($data['about_txt'])) {
            $data['_attr']['相關資料'] = $data['about_txt'];
        }

        //產品評分、年齡分佈
        $data1 = $this->Lookup->getLookup('agegroup');

        $data5 = $this->Lookup->getLookup('body_skin'); //膚質
        //好評度（很好、好、一般、差、很差）
        $data2 = $this->Lookup->getLookup('product_reports_well');

        //獲得報告列表資料
        $data3 = $this->ProductReports->getReportsList($pid, 0, $rid, 'TB1.id desc', 1, 1, $pure);

        $data3_res = $data3['result'][0];
        if (!empty($data3_res)) {
            $data3_res['photo_l'] = PhotoResize($data3_res['photo'], 77, 77);
            //用戶報告圖文
            if (!empty($data3_res['content_json'])) {
                $data3_res['_content'] = json_decode($data3_res['content_json'], true);
            }

            //用戶滿意度
            $j = 0;
            for ($i = 1; $i < 9; $i++) {
                if (isset($data['vote_option_data']['result'][$i - 1]) && !empty($data['vote_option_data']['result'][$i - 1])) {
                    $data3_res['_category_score'][$j]['k'] = $data3_res['category_score' . $i];
                    $data3_res['_category_score'][$j]['v'] = $data['vote_option_data']['result'][$i - 1]['cname'];
                    $j++;
                }
            }

            //是否已關注該用戶
            if (!empty($this->member)) {
                $_islike = $this->MemberLike->getMemberLike($this->member['id'], 'member', $data3_res['mid']);
            } else {
                $_islike = 0;
            }
            $data3_res['islike'] = !empty($_islike) ? 1 : 0;
        }

        //上一頁、下一頁
        if (!empty($data3['previous'])) {
            $data3_res['previous'] = $data3['previous'];
        } else {
            $data3_res['previous']['id'] = 0;
            $data3_res['previous']['title'] = '沒有了';
        }
        if (!empty($data3['next'])) {
            $data3_res['next'] = $data3['next'];
        } else {
            $data3_res['next']['id'] = 0;
            $data3_res['next']['title'] = '沒有了';
        }

        $order = $this->get_q('order', 2, 'int');
        switch ($order) {
            case 2:
                $orderby = "TB1.addtime desc,TB1.id desc";
                break;
            case 3:
                $orderby = "TB1.addtime asc,TB1.id desc";
                break;
            case 4:
                $orderby = "TB1.subComments desc,TB1.id desc";
                break;
            case 1:
            default:
                $orderby = "TB1.likes desc,TB1.id desc";
                break;
        }
        $data4 = $this->ProductReportsComment->getReportsCommentList($rid, $orderby, $page, $this->pagesize);
        if (!empty($data4['result'])) {
            foreach ($data4['result'] as $k => $v) {
                $data4['result'][$k]['photo_l'] = PhotoResize($v['photo'], 58, 58);
                $data4['result'][$k]['addtime'] = time_to_str($v['addtime']);
            }
        }
        //fb likes
        $data['_fb_likes'] = db_query_count('member_good', "section='product' and sid=" . $pid);



        $pagelist = showPage($data4['pageinfo']['total'], $this->pagesize, $page, 'product.php?action=reportDetail&mtype=' . $mtype . '&order=' . $order . '&pid=' . $pid . '&rid=' . $rid, 0, '&#messagebox');

        $uid = empty($this->member) ? 0 : $this->member['id'];
        $photo = empty($this->member) ? PhotoResize('', 58, 58) : PhotoResize($this->member['photo'], 58, 58);

        $reply_type = 0; //  0 -itrial 自己的留言下，自己的回覆可移除，別人的可舉報   1 -gotrip 自己的留言下，所有回覆可移除
//echo '<pre>'.var_export($data3_res,1).'</pre>';
        $this->tmpl_assign('pure', $pure);
        $this->tmpl_assign('reply_type', $reply_type);
        $this->tmpl_assign('uid', $uid);
        $this->tmpl_assign('photo', $photo);
        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('rid', $rid);
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('data', $data);
        $this->tmpl_assign('data1', $data1);
        $this->tmpl_assign('data2', $data2);
        $this->tmpl_assign('data3_res', $data3_res);
        $this->tmpl_assign('data4', $data4);
        $this->tmpl_assign('data5', $data5);
        $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
        $this->tmpl_assign('pageValue', $pageValue);
        return $this->load_tmpl($tmpl);
    }

    function action_readReport_list() {
        $page = $this->get_q('page', 1, 'int');
        $order = $this->get_q('order', 1, 'int');
        $ptype = $this->get_q('ptype', 0, 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        $tmpl = $mtype == 5 ? 'p_readReport_list_expert.php' : 'p_readReport_list_general.php';

        // <!--數據列表
        switch ($order) {
            case 3:
                $orderby = "TB1.reports desc,TB1.id desc";
                break;
            case 2:
                $orderby = "scores desc,TB1.id desc";
                break;
            case 1:
            default:
                $orderby = "TB1.report_endtime desc,TB1.id desc";
                break;
        }

        $data = $this->Product->getProductList($mtype, 3, $orderby, $page, $this->pagesize, '', $ptype);
        $res = isset($data['result']) && !empty($data['result']) ? $data['result'] : array();
        $data2 = array();
        foreach ($res as $k => $v) {
            $res[$k]['_photo_url'] = PhotoResize($v['cover'], 158, 107);
            //總評

            $res[$k]['_overall'] = ($res[$k]['scores']) ? round($res[$k]['scores']) : 0;

            $res[$k]['_reports'] = $res[$k]['reports'];
            $res[$k]['_real_volume'] = $res[$k]['capacity_trial'];
            $data2[$k] = $this->ProductReports->getReportsList($v['id'], 0, 0, "TB1.id desc", 1, 5);
            foreach ($data2[$k]['result'] as $k1 => $v1) {
                $data2[$k]['result'][$k1]['photo_l'] = PhotoResize($v1['photo'], 56, 56);
            }
            //報告總數
            $res[$k]['_rpsum'] = $data2[$k]['pageinfo']['total'];
        }

        //分類
        $data3 = $this->Lookup->getLookup('product_layout_category', 0, 1, 9);
        $ptype_arr = array();
        $ptype_arr[0] = '所有分類';
        foreach ($data3['result'] as $k => $v) {
            $ptype_arr[$v['id']] = $v['cname'];
        }

        //end 數據列表-->
        //echo '<pre>'.var_export($data2,1).'</pre>';

        $pagelist = showPage($data['pageinfo']['total'], $this->pagesize, $page, 'product.php?action=readReport_list&mtype=' . $mtype . '&ptype=' . $ptype . '&order=' . $order);


        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('ptype_arr', $ptype_arr);
        $this->tmpl_assign('ptype', $ptype);
        $this->tmpl_assign('result', $res);
        $this->tmpl_assign('order', $order);
        $this->tmpl_assign('data2', $data2);
        $this->tmpl_assign('mtype', $mtype);
        return $this->load_tmpl($tmpl);
    }

    function action_report_show() {
        $pid = $this->get_q('pid', 1, 'int');
        $aid = $this->get_q('aid', 1, 'int');
        $issub = $this->get_q('issubmit', 0);

        $memberData = $this->s_param('memberData');
        if (!$memberData) {
            $toURL = $this->selfurl . '?action=report_show&pid=' . $pid . "&aid=" . $aid . "&issubmit=" . $issub;
            $this->s_param('toURL', $toURL);
            return showMsgCode(HAS_LOGIN, 'member.php?action=login');
        }


        $data = $this->Product->getProductById($pid);
        if (!empty($issub)) {
            $or = $this->get_q('or', 9, 'int');
            $res = db_update('product_application', array('application_status' => $or), 'id=' . $aid);
            $msg = $or == 9 ? json_encode('你已接受邀請‘' . $data['cname'] . '’，請於‘' . $data['report_endtime'] . '’前提交報告！') : json_encode('你已拒絕邀請‘' . $data['cname'] . '’！');
            if ($res) {
                $attr = array();
                $attr['mid'] = $this->member['id'];
                $attr['product'] = $pid;
                $attr['delivery_status'] = 1;
                $attr['report_endtime'] = $data['report_endtime'];
                $attr['delivery_status'] = 1;
                $attr['status'] = 1;
                $res2 = db_add('member_application', $attr);
                if ($res2) {
                    header('Location:member_center.php?action=invite&msg=' . $msg);
                } else {
                    exit('error');
                }
            }
        } else {
            $data['_photo_url'] = PhotoResize($data['cover'], 180, 180);
            //體驗天數
            $data['_diff_day'] = (int) ((strtotime($data['report_endtime']) - strtotime($data['apply_starttime'])) / 86400);
            //right 產品屬性info
            $attr = array();
            if (!empty($data['price_trial'])) {
                $data['_attr']['價格'] = $data['price_trial'];
            }
            if (!empty($data['capacity_trial'])) {
                $data['_attr']['容量'] = $data['capacity_trial'];
            }
            for ($i = 1; $i < 9; $i++) {
                if (!empty($data['attribute_value' . $i])) {
                    $data['_attr'][$data['attribute_label' . $i]] = $data['attribute_value' . $i];
                }
            }

            $bt_url = array();
            $bt_url[1] = 'product.php?action=report_show&issubmit=1&pid=' . $pid . '&aid=' . $aid . '&or=9';
            $bt_url[2] = 'product.php?action=report_show&issubmit=1&pid=' . $pid . '&aid=' . $aid . '&or=11';

            $mtxt = $data['member_type'] == 5 ? '體驗' : '試用';
            $this->tmpl_assign('mtxt', $mtxt);
            $this->tmpl_assign('bt_url', $bt_url);
            $this->tmpl_assign('data', $data);
            $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
            $this->tmpl_assign('pageValue', $pageValue);
        }
        //echo '<pre>'.var_export($data,1).'</pre>';
        return $this->load_tmpl("p_report_show.php");
    }

    function action_report_add() {
        $pid = $this->get_q('pid', 1, 'int');
        $mtype = $this->get_q('mtype', 1, 'int');
        if ($this->get_q('issubmit') == 'true') {
            if (empty($this->member)) {
                $this->iframeReturn(null, 'callback', array('retcode' => 6, 'msg' => NO_LOGIN));
            }
            $attr = $pic = $pic_c = array();
            $attr['oid'] = $pid;
            $attr['mid'] = $this->member['id'];

            $attr['title'] = htmlspecialchars($this->get_q('title', ''));
            if (empty($attr['title'])) {
                $this->iframeReturn(null, 'callback', array('retcode' => 1, 'msg' => HAS_REPORT_TITLE));
            }

            $attr['agegroup'] = $this->get_q('age', 1, 'int');
            $attr['body_skin'] = $this->get_q('skin', 1, 'int');

            $attr['well'] = $this->get_q('well', 1, 'int');
            for ($i = 1; $i < 9; $i++) {
                $attr['category_score' . $i] = $this->get_q('category_score' . $i, 0, 'int');
            }

            $_pic = $this->get_q('pic', '');
            $_pic_c = $this->get_q('pic_c', '');
            $pic_c = array();
            foreach ($_pic as $k => $v) {
                if (!empty($v['p'])) {
                    if (empty($v['t']) || strlen($v['t']) < 50) {
                        $this->iframeReturn(array($k), 'callback', array('retcode' => 3, 'msg' => HAS_MORE_TXT_50));
                    }
                    $pic[$k] = $v;
                    if (in_array($_pic_c[$k], $pic_c)) {
                        $this->iframeReturn(array($k), 'callback', array('retcode' => 3, 'msg' => ERR_SAME_PIC));
                    } else {
                        $pic_c[] = $_pic_c[$k];
                    }
                }
            }

            if ($mtype == 5) {
                if (count($pic) < 5) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 2, 'msg' => HAS_MORE_PIC_5));
                }
            } else {
                if (count($pic) < 2) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 2, 'msg' => HAS_MORE_PIC_2));
                }
            }
            $attr['content_json'] = json_encode($pic);

            $attr['body'] = htmlspecialchars($this->get_q('content', ''));
            if (empty($attr['body']) || strlen($attr['body']) < 100 || strlen($attr['body']) > 250) {
                $this->iframeReturn(null, 'callback', array('retcode' => 4, 'msg' => HAS_MORE_TXT_100));
            }

            $attr['is_valid'] = 0;
            $attr['status'] = 3;
            $attr['addtime'] = date('Y-m-d H:i:s');

            //echo '<pre>'.var_export($attr,1).'</pre>';

            $res2 = db_add(' product_reports', $attr);
            if ($res2) {
                db_update('member_application', array('is_submitted' => 1), ' product=' . $pid . ' and mid=' . $this->member['id'] . ' and status=1');
                $this->iframeReturn(array('id' => $res2), 'callback', array('retcode' => 5, 'msg' => 'success'));
            } else {
                $this->iframeReturn(null, 'callback', array('retcode' => 6, 'msg' => 'error'));
            }
        } else {
            $data = $this->Product->getProductById($pid);
            $data['_photo_url'] = PhotoResize($data['cover'], 180, 180);

            //體驗天數
            $data['_diff_day'] = (int) ((strtotime($data['report_endtime']) - strtotime($data['apply_starttime'])) / 86400);
            //right 產品屬性info
            $attr = array();
            for ($i = 1; $i < 9; $i++) {
                if (!empty($data['attribute_value' . $i])) {
                    $data['_attr'][$data['attribute_label' . $i]] = $data['attribute_value' . $i];
                }
            }

            $data1 = $this->Lookup->getLookup('agegroup'); //年齡段
            $data2 = $this->Lookup->getLookup('body_skin'); //膚質
            $data3 = $this->Lookup->getLookup('product_reports_well'); //滿意度  很好、好
            $data4 = $data['vote_option_data']; //好評  美白度
            //echo '<pre>'.var_export($data3,1).'</pre>';
            $arr5 = array(1, 2, 3, 4, 5);
            $arr10 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            $arr5_10 = $mtype == 5 ? $arr10 : $arr5;
            $mtxt = $mtype == 5 ? '體驗' : '試用';
            $this->tmpl_assign('mtxt', $mtxt);
            $this->tmpl_assign('arr5', $arr5);
            $this->tmpl_assign('arr5_10', $arr5_10);
            $this->tmpl_assign('selfurl', $this->selfurl);
            $this->tmpl_assign('pid', $pid);
            $this->tmpl_assign('mtype', $mtype);
            $this->tmpl_assign('data', $data);
            $this->tmpl_assign('data1', $data1);
            $this->tmpl_assign('data2', $data2);
            $this->tmpl_assign('data3', $data3);
            $this->tmpl_assign('data4', $data4);
            $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
            $this->tmpl_assign('pageValue', $pageValue);
            return $this->load_tmpl("p_report_add.php");
        }
    }

    function action_ajax() {
        $t = $this->get_q('t', 1, 'int');
        switch ($t) {
            case 1:
                $topid = $this->get_q('topid', 1, 'int');
                $page = $this->get_q('page', 1, 'int');
                $data = $this->ProductReportsComment->getReportsSubCommentList($topid, "TB1.id desc", $page, 2);
                $_res = db_query_one('product_reports_comment', array('field' => 'mid', 'where' => 'id=' . $topid));
                foreach ($data['result'] as $k => $v) {
                    $data['result'][$k]['photo_l'] = PhotoResize($v['photo'], 58, 58);
                    $data['result'][$k]['top_mid'] = $_res['result']['mid'];
                    $data['result'][$k]['addtime'] = time_to_str($v['addtime']);
                }
                //print_r($data);
                exit(json_encode($data));
                break;
            case 2:
                if (empty($this->member)) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 1, 'msg' => NO_LOGIN));
                }
                $attr = array();
                $attr['oid'] = $this->get_q('rid', 1, 'int');
                $attr['topid'] = $this->get_q('linkid', 0, 'int');
                $attr['mid'] = $this->member['id'];
                $attr['body'] = htmlspecialchars($this->get_q('message', ''));
                $attr['status'] = 1;
                $attr['addtime'] = date("Y-m-d H:i:s");
                $attr['likes'] = 0;
                $attr['unlikes'] = 0;
                if (empty($attr['body'])) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 1, 'msg' => ERR_RESPONSES_EMPTY));
                }

                $retcode = 1;
                $retmsg = 'success';
                $res = db_add('product_reports_comment', $attr);
                if ($res) {
                    $attr['id'] = $res;
                    //$attr['body'] = $_body;
                    $attr['username'] = $this->member['username'];
                    $attr['photo_l'] = PhotoResize($this->member['photo'], 58, 58);

                    if (empty($attr['topid'])) {
                        $res1 = db_query_one('product_reports', array('field' => 'comments', 'where' => ' id=' . $attr['oid']));
                        $reps = $res1['result']['comments'] + 1;
                        db_update('product_reports', array('comments' => $reps), ' id=' . $attr['oid']);

                        $attr['sum'] = 0;
                        $retcode = 3;
                        $retmsg = 'error';
                    } else {
                        $_sum = $this->get_q('sum', 0, 'int');
                        $attr['sum'] = $_sum + 1;
                        db_update('product_reports_comment', array('subComments' => $attr['sum']), 'id=' . $attr['topid']);
                        $retcode = 2;
                        $retmsg = 'error';
                    }
                }
                $attr['addtime'] = '剛剛';
                $this->iframeReturn($attr, 'callback', array('retcode' => $retcode, 'msg' => $retmsg));
                break;
            case 3:
                if (!empty($this->member)) {
                    $sec = $this->get_q('sec', '');
                    $sid = $this->get_q('sid', 0, 'int');
                    $type = $this->get_q('type', 1, 'int'); // 回覆good bad
                    $attr = array();
                    $attr['section'] = $sec;
                    $attr['mid'] = $this->member['id'];
                    $attr['sid'] = $sid;
                    $attr['addtime'] = date('Y-m-d H:i:s');
                    $c = db_query_count('member_like', "section='" . $sec . "' and mid=" . $this->member['id'] . " and sid=" . $sid);
                    $recode = $likes = 0;
                    $like_field = ($sec == 'comment' && $type == 2) ? 'unlikes' : 'likes';
                    if ($c < 1) {
                        $res = db_add('member_like', $attr);
                        if ($res > 0) {
                            switch ($sec) {
                                case 'product': $tbn = 'product';
                                    break;
                                case 'report': $tbn = 'product_reports';
                                    break;
                                case 'comment': $tbn = 'product_reports_comment';
                                    break;
                                default : exit;
                            }
                            $_data = db_query_one($tbn, array('field' => $like_field, 'where' => 'id=' . $sid . ' and status=1'));
                            $likes = intval($_data['result'][$like_field]) + 1;
                            $res1 = db_update($tbn, array($like_field => $likes), 'id=' . $sid . ' and status=1');
                            $recode = empty($res1) ? $recode : 1;
                        }
                    }
                    echo json_encode(array('recode' => $recode, 'likes' => $likes, 'msg' => HAS_LIKES));
                } else {
                    echo json_encode(array('recode' => 2, 'likes' => 0, 'msg' => NO_LOGIN));
                }
                exit();
                break;
            case 4:
                if (empty($this->member)) {
                    echo json_encode(array('recode' => 0, 'msg' => NO_LOGIN));
                    exit();
                }
                $attr = array();
                $attr['comment_id'] = $this->get_q('id', 1, 'int');
                $attr['comment_mid'] = $this->get_q('mid', 1, 'int'); //被舉報者
                $attr['inform_mid'] = $this->member['id']; ////////舉報者
                $attr['addtime'] = date("Y-m-d H:i:s");

                $c = db_query_count('comment_inform', "comment_id=" . $attr['comment_id'] . " and comment_mid=" . $attr['comment_mid'] . " and inform_mid=" . $attr['inform_mid']);
                if ($c > 0) {
                    echo json_encode(array('recode' => 2, 'msg' => HAS_COMMENT));
                    exit();
                }
                $res = db_add('comment_inform', $attr);
                echo json_encode(array('recode' => 1, 'msg' => ''));
                exit();
                break;
            case 5:
                $id = $this->get_q('id', 0, 'int');
                $topid = $this->get_q('topid', 0, 'int');
                $sum = $this->get_q('sum', 0, 'int');
                $is = $this->get_q('is', 0, 'int');

                $res = db_update('product_reports_comment', array('status' => 0), 'id=' . $id);
                if (!empty($is)) {
                    $res = db_query_one('product_reports_comment', array('field' => 'oid', 'where' => ' id=' . $id));
                    $res1 = db_query_one('product_reports', array('field' => 'comments', 'where' => ' id=' . $res['result']['oid']));
                    $reps = $res1['result']['comments'] - 1;
                    db_update('product_reports', array('comments' => $reps), ' id=' . $res['result']['oid']);
                }
                if (!empty($topid)) {
                    db_update('product_reports_comment', array('subComments' => ($sum - 1)), 'id=' . $topid);
                }
                echo $res;
                exit();
                break;
            case 6:
                global $site_global_config;
                $root = $site_global_config['WWW'];
                $upload_status = uploadfiles($root . '/upload/invite', 'temp', "jpg,jpeg,gif,png", 512000);
                foreach ($upload_status as $k => $v) {
                    if ($v['code'] === 1) {
                        $upload_status[$k]['src'] = FB_REDIRECT_URI . str_replace($root, '', $upload_status[$k]['path']);
                        $upload_status[$k]['thumb'] = PhotoResize($upload_status[$k]['path'], 56, 56);
                    }
                }
                echo '<script>' . str_replace('$res', json_encode($upload_status), $_POST['callback_script']) . '</script>';
                break;
            case 7:
                $pic1 = $this->get_q('pic1', '');
                $pic2 = $this->get_q('pic2', '');
                if (!empty($pic1) && !empty($pic1)) {
                    unlink($pic1);
                    unlink($pic2);
                    echo '1';
                } else {
                    echo 'error';
                }
                break;
            case 8:
                global $site_global_config;
                $root = $site_global_config['WWW'];

                $upload_status = uploadfiles($root . '/upload/report');
                $pic_id = $this->get_q('pic_id', '');
                foreach ($upload_status as $k => $v) {
                    if ($v['code'] === 1) {
                        $upload_status[$k]['src'] = FB_REDIRECT_URI . str_replace($root, '', $upload_status[$k]['path']);
                        $upload_status[$k]['thumb'] = PhotoResize($upload_status[$k]['path'], 100, 100);
                        $upload_status[$k]['pic_id'] = $pic_id;
                    }
                }
                echo '<script>' . str_replace('$res', json_encode($upload_status), $_POST['callback_script']) . '</script>';
                break;
            case 9:
                $pid = $this->get_q('pid', 0, 'int');
                $_date_res = db_query_one('member_application', array('field' => 'report_endtime', 'where' => 'product=' . $pid . ' and mid=' . $this->member['id']));
                $_date = date('Y-m-d H:i:s', strtotime($_date_res['result']['report_endtime']) + 604800);
                $res = db_update('member_application', array('is_member_delay' => 1, 'report_endtime' => $_date), 'product=' . $pid . ' and mid=' . $this->member['id']);
                if ($res) {
                    $attr = array();
                    $data = $this->Product->getProductById($pid);
                    $attr['pid'] = $pid;
                    $attr['type_name'] = $data['type_name'];
                    $attr['cname'] = $data['cname'];
                    $attr['date'] = $_date;
                    $attr['date_l'] = date('Y-m-d', strtotime($_date));
                }
                $this->iframeReturn($attr, 'callback', array('retcode' => 1, 'msg' => 'success'));
                break;
            case 10:
                $ret = array();
                if (!empty($this->member)) {
                    $ret['login'] = 1;

                    $_mem = $this->ModelMember->getMemberCondition($this->member['id']);
                    $_member_arr = array();
                    if ($_mem['result'])
                        $_member_arr = $_mem['result'][0];

                    $pid = $this->get_q('pid', 0, 'int');
                    $_pdata = db_query_one('product', array('field' => 'member_type', 'where' => 'id=' . $pid));

                    if (!$_member_arr['address']) {
                        $ret['limit'] = 0;
                        $ret['msg1'] = LIMIT_INVITE;
                    } elseif ((!$_member_arr['homepage']) && intval($_pdata['result']['member_type']) == 5) {
                        $ret['limit'] = 0;
                        $ret['msg1'] = LIMIT_INVITE_EXPERIENCE;
                    } else {
                        $ret['limit'] = 1;
                    }

                    $_data = db_query_count('product_application', "oid=" . $pid . " and mid=" . $this->member['id']);
                    if ($_data > 0) {
                        $ret['invite'] = 0;
                        $ret['msg2'] = HAS_APPLY;
                    } else {
                        $ret['invite'] = 1;
                    }
                } else {
                    $ret['login'] = 0;
                    $ret['msg3'] = NO_LOGIN;
                }
                echo json_encode($ret);
                exit();
                break;
            case 11:
                $ret = array();
                if (!empty($this->member)) {
                    $ret['login'] = 1;
                    $pid = $this->get_q('pid', 0, 'int');
                    $_data = db_query_count('product_application', 'mid=' . $this->member['id'] . ' and oid=' . $pid . ' and application_status=9 and status=1');
                    if ($_data > 0) {
                        $_data1 = db_query_one('product', array('field' => 'report_starttime', 'where' => 'id=' . $pid));
                        $_data2 = db_query_one('member_application', array('field' => 'report_endtime', 'where' => 'mid=' . $this->member['id'] . ' and product=' . $pid . '  and status=1'));
                        if (time() >= strtotime($_data1['result']['report_starttime']) && time() <= strtotime($_data2['result']['report_endtime'])) {
                            $ret['report'] = 1;
                        } else {
                            $ret['report'] = 0;
                            $ret['msg'] = CANNOT_REPORT;
                        }
                    } else {
                        $ret['report'] = 0;
                        $ret['msg'] = CANNOT_REPORT;
                    }
                } else {
                    $ret['login'] = 0;
                    $ret['msg'] = NO_LOGIN;
                }
                echo json_encode($ret);
                exit();
                break;
            case 12:
                if (!empty($this->member)) {
                    $sec = $this->get_q('sec', '');
                    $sid = $this->get_q('sid', 0, 'int');
                    $attr = array();
                    $attr['section'] = $sec;
                    $attr['mid'] = $this->member['id'];
                    $attr['sid'] = $sid;
                    $attr['addtime'] = date('Y-m-d H:i:s');
                    $c = db_query_count('member_good', "section='" . $sec . "' and mid=" . $this->member['id'] . " and sid=" . $sid);
                    $cc = 0;
                    if ($c < 1) {
                        $res = db_add('member_good', $attr);
                        if ($res > 0) {
                            $cc = db_query_count('member_good', "section='" . $sec . "' and sid=" . $sid);
                            echo json_encode(array('recode' => 1, 'likes' => $cc, 'msg' => 'success'));
                        } else {
                            echo json_encode(array('recode' => 0, 'likes' => $cc, 'msg' => 'tb error'));
                        }
                    } else {
                        echo json_encode(array('recode' => 0, 'likes' => $cc, 'msg' => HAS_LIKES));
                    }
                } else {
                    echo json_encode(array('recode' => 2, 'likes' => 0, 'msg' => NO_LOGIN));
                }
                exit();
                break;
            default:
                echo 'default error';
                break;
        }
    }

    function action_test_report() {

        if ($this->get_q('issubmit')) {
            $pid = $this->get_q('pid', 1, 'int');
            $rid = $this->get_q('rid', 1, 'int');
            $_isexit1 = db_query_count('product_reports', ' id=' . $rid);
            if ($_isexit1 < 1)
                exit('輸入報告id無效！');
            $_isexit2 = db_query_count('product_reports', ' id=' . $rid . ' and status=1 and is_valid=1');
            if ($_isexit2 > 0)
                exit('此報告已登刊！');

            db_update('product_reports', array('is_valid' => 1, 'status' => 1), 'id=' . $rid);

            $res1 = db_query_one('product', array('field' => 'reports', 'where' => 'id=' . $pid));

            $_count = db_query_count('product_reports', ' oid=' . $pid . ' and mid=' . $this->member['id'] . ' and status=1 and is_valid=1');

            if (intval($_count) > 1) {
                db_update('product_reports', array('is_valid' => 0), ' oid=' . $pid . ' and mid=' . $this->member['id'] . ' and id !=' . $rid);
            } else {
                $reps = intval($res1['result']['reports']) + 1;
                db_update('product', array('reports' => $reps), ' id=' . $pid);
            }

            $product_data = db_query_one('product', array('where' => 'id =' . $pid . ' and status=1'));
            if ($product_data['result']) {
                $value = $product_data['result'];

                $id = $value['id'];


                $well = $this->dbMove->product_reports_average('well', $id);
                $category_score1 = $this->dbMove->product_reports_average('category_score1', $id);
                $category_score2 = $this->dbMove->product_reports_average('category_score2', $id);
                $category_score3 = $this->dbMove->product_reports_average('category_score3', $id);
                $category_score4 = $this->dbMove->product_reports_average('category_score4', $id);
                $category_score5 = $this->dbMove->product_reports_average('category_score5', $id);
                $category_score6 = $this->dbMove->product_reports_average('category_score6', $id);
                $category_score7 = $this->dbMove->product_reports_average('category_score7', $id);
                $category_score8 = $this->dbMove->product_reports_average('category_score8', $id);

                $data = $this->dbMove->product_reports_groupby('well', $id);

                $count_well1 = $count_well2 = $count_well3 = $count_well4 = $count_well5 = 0;
                $count_agegroup1 = $count_agegroup2 = $count_agegroup3 = $count_agegroup4 = $count_agegroup5 = $count_agegroup6 = 0;

                if ($data) {
                    foreach ($data as $key => $value) {
                        switch ($value['well']) {
                            case 1:
                                $count_well1 = $value['count'];
                                break;
                            case 2:
                                $count_well2 = $value['count'];
                                break;
                            case 3:
                                $count_well3 = $value['count'];
                                break;
                            case 4:
                                $count_well4 = $value['count'];
                                break;
                            case 5:
                                $count_well5 = $value['count'];
                                break;
                            default:
                                break;
                        }
                    }
                }

                $data = $this->dbMove->product_reports_groupby('agegroup', $id);
                if ($data) {
                    foreach ($data as $key => $value) {
                        switch ($value['agegroup']) {
                            case 1:
                                $count_agegroup1 = $value['count'];
                                break;
                            case 2:
                                $count_agegroup2 = $value['count'];
                                break;
                            case 3:
                                $count_agegroup3 = $value['count'];
                                break;
                            case 4:
                                $count_agegroup4 = $value['count'];
                                break;
                            case 5:
                                $count_agegroup5 = $value['count'];
                                break;
                            case 6:
                                $count_agegroup6 = $value['count'];
                                break;
                            default:
                                break;
                        }
                    }
                }

                $insert_data['id'] = $id;
                $insert_data['oid'] = $id;
                $insert_data['well'] = $well ? $well : 0;
                $insert_data['category_score_num'] = ($count_well1 + $count_well2 + $count_well3 + $count_well4 + $count_well5) ? ($count_well1 + $count_well2 + $count_well3 + $count_well4 + $count_well5) : 0;
                $insert_data['category_score1'] = $category_score1 ? $category_score1 : 0;
                $insert_data['category_score2'] = $category_score2 ? $category_score2 : 0;
                $insert_data['category_score3'] = $category_score3 ? $category_score3 : 0;
                $insert_data['category_score4'] = $category_score4 ? $category_score4 : 0;
                $insert_data['category_score5'] = $category_score5 ? $category_score5 : 0;
                $insert_data['category_score6'] = $category_score6 ? $category_score6 : 0;
                $insert_data['category_score7'] = $category_score7 ? $category_score7 : 0;
                $insert_data['category_score8'] = $category_score8 ? $category_score8 : 0;
                $insert_data['well_score_num1'] = $count_well1 ? $count_well1 : 0;
                $insert_data['well_score_num2'] = $count_well2 ? $count_well2 : 0;
                $insert_data['well_score_num3'] = $count_well3 ? $count_well3 : 0;
                $insert_data['well_score_num4'] = $count_well4 ? $count_well4 : 0;
                $insert_data['well_score_num5'] = $count_well5 ? $count_well5 : 0;
                $insert_data['agegroup1'] = $count_agegroup1 ? $count_agegroup1 : 0;
                $insert_data['agegroup2'] = $count_agegroup2 ? $count_agegroup2 : 0;
                $insert_data['agegroup3'] = $count_agegroup3 ? $count_agegroup3 : 0;
                $insert_data['agegroup4'] = $count_agegroup4 ? $count_agegroup4 : 0;
                $insert_data['agegroup5'] = $count_agegroup5 ? $count_agegroup5 : 0;
                $insert_data['agegroup6'] = $count_agegroup6 ? $count_agegroup6 : 0;

                $insertkeyvalue = $insertvalue = '';
                if ($insert_data) {
                    foreach ($insert_data as $key => $result) {
                        $insertkeyvalue.= $insertkeyvalue ? " ," . $key : $key;
                        $insertvalue.= $insertvalue ? " ,'" . $result . "'" : "'" . $result . "'";
                    }
                }

                $sql = "REPLACE INTO  product_reports_stat  ($insertkeyvalue)
			VALUES($insertvalue)";

                $param = array();
                db_handle($sql, $param);
            }

            exit("報告登刊成功");
        } else {
            $str = "報告審核（測試）<br/><form action='product.php?action=test_report' method='post'>";
            $str .= "產品id<input type='text' name='pid'/><br/>";
            $str .= "報告id<input type='text' name='rid'/><br/>";
            $str .= "<input type='hidden' name='issubmit' value='true' /><br/>";
            $str .= "<input type='submit' name='submit' value='立即審核' />";
            $str .= "</form>";
            echo $str;
        }
    }

    function action_approveReport() {

        $pid = $this->get_q('pid', 1, 'int');
        $rid = $this->get_q('rid', 1, 'int');
        $key = $this->get_q('key');

        if ($key <> md5($pid . $rid . "imoreHK"))
            exit();

        $_isexit1 = db_query_count('product_reports', ' id=' . $rid);
        if ($_isexit1 < 1)
            exit('輸入報告id無效！');
        $_isexit2 = db_query_count('product_reports', ' id=' . $rid . ' and status=1 and is_valid=1');
        if ($_isexit2 > 0)
            exit('此報告已登刊！');

        db_update('product_reports', array('is_valid' => 1, 'status' => 1), 'id=' . $rid);

        $res1 = db_query_one('product', array('field' => 'reports', 'where' => 'id=' . $pid));

        $_count = db_query_count('product_reports', ' oid=' . $pid . ' and mid=' . $this->member['id'] . ' and status=1 and is_valid=1');

        if (intval($_count) > 1) {
            db_update('product_reports', array('is_valid' => 0), ' oid=' . $pid . ' and mid=' . $this->member['id'] . ' and id !=' . $rid);
        } else {
            $reps = intval($res1['result']['reports']) + 1;
            db_update('product', array('reports' => $reps), ' id=' . $pid);
        }

        $product_data = db_query_one('product', array('where' => 'id =' . $pid . ' and status=1'));
        if ($product_data['result']) {
            $value = $product_data['result'];

            $id = $value['id'];


            $well = $this->dbMove->product_reports_average('well', $id);
            $category_score1 = $this->dbMove->product_reports_average('category_score1', $id);
            $category_score2 = $this->dbMove->product_reports_average('category_score2', $id);
            $category_score3 = $this->dbMove->product_reports_average('category_score3', $id);
            $category_score4 = $this->dbMove->product_reports_average('category_score4', $id);
            $category_score5 = $this->dbMove->product_reports_average('category_score5', $id);
            $category_score6 = $this->dbMove->product_reports_average('category_score6', $id);
            $category_score7 = $this->dbMove->product_reports_average('category_score7', $id);
            $category_score8 = $this->dbMove->product_reports_average('category_score8', $id);

            $data = $this->dbMove->product_reports_groupby('well', $id);

            $count_well1 = $count_well2 = $count_well3 = $count_well4 = $count_well5 = 0;
            $count_agegroup1 = $count_agegroup2 = $count_agegroup3 = $count_agegroup4 = $count_agegroup5 = $count_agegroup6 = 0;

            if ($data) {
                foreach ($data as $key => $value) {
                    switch ($value['well']) {
                        case 1:
                            $count_well1 = $value['count'];
                            break;
                        case 2:
                            $count_well2 = $value['count'];
                            break;
                        case 3:
                            $count_well3 = $value['count'];
                            break;
                        case 4:
                            $count_well4 = $value['count'];
                            break;
                        case 5:
                            $count_well5 = $value['count'];
                            break;
                        default:
                            break;
                    }
                }
            }

            $data = $this->dbMove->product_reports_groupby('agegroup', $id);
            if ($data) {
                foreach ($data as $key => $value) {
                    switch ($value['agegroup']) {
                        case 1:
                            $count_agegroup1 = $value['count'];
                            break;
                        case 2:
                            $count_agegroup2 = $value['count'];
                            break;
                        case 3:
                            $count_agegroup3 = $value['count'];
                            break;
                        case 4:
                            $count_agegroup4 = $value['count'];
                            break;
                        case 5:
                            $count_agegroup5 = $value['count'];
                            break;
                        case 6:
                            $count_agegroup6 = $value['count'];
                            break;
                        default:
                            break;
                    }
                }
            }

            $insert_data['id'] = $id;
            $insert_data['oid'] = $id;
            $insert_data['well'] = $well ? $well : 0;
            $insert_data['category_score_num'] = ($count_well1 + $count_well2 + $count_well3 + $count_well4 + $count_well5) ? ($count_well1 + $count_well2 + $count_well3 + $count_well4 + $count_well5) : 0;
            $insert_data['category_score1'] = $category_score1 ? $category_score1 : 0;
            $insert_data['category_score2'] = $category_score2 ? $category_score2 : 0;
            $insert_data['category_score3'] = $category_score3 ? $category_score3 : 0;
            $insert_data['category_score4'] = $category_score4 ? $category_score4 : 0;
            $insert_data['category_score5'] = $category_score5 ? $category_score5 : 0;
            $insert_data['category_score6'] = $category_score6 ? $category_score6 : 0;
            $insert_data['category_score7'] = $category_score7 ? $category_score7 : 0;
            $insert_data['category_score8'] = $category_score8 ? $category_score8 : 0;
            $insert_data['well_score_num1'] = $count_well1 ? $count_well1 : 0;
            $insert_data['well_score_num2'] = $count_well2 ? $count_well2 : 0;
            $insert_data['well_score_num3'] = $count_well3 ? $count_well3 : 0;
            $insert_data['well_score_num4'] = $count_well4 ? $count_well4 : 0;
            $insert_data['well_score_num5'] = $count_well5 ? $count_well5 : 0;
            $insert_data['agegroup1'] = $count_agegroup1 ? $count_agegroup1 : 0;
            $insert_data['agegroup2'] = $count_agegroup2 ? $count_agegroup2 : 0;
            $insert_data['agegroup3'] = $count_agegroup3 ? $count_agegroup3 : 0;
            $insert_data['agegroup4'] = $count_agegroup4 ? $count_agegroup4 : 0;
            $insert_data['agegroup5'] = $count_agegroup5 ? $count_agegroup5 : 0;
            $insert_data['agegroup6'] = $count_agegroup6 ? $count_agegroup6 : 0;

            $insertkeyvalue = $insertvalue = '';
            if ($insert_data) {
                foreach ($insert_data as $key => $result) {
                    $insertkeyvalue.= $insertkeyvalue ? " ," . $key : $key;
                    $insertvalue.= $insertvalue ? " ,'" . $result . "'" : "'" . $result . "'";
                }
            }

            $sql = "REPLACE INTO  product_reports_stat  ($insertkeyvalue)
			VALUES($insertvalue)";

            $param = array();
            db_handle($sql, $param);
        }

        exit("報告登刊成功");
    }

    function action_emailApplication() {

        $aid = $this->get_q('aid', 1, 'int');
        $key = $this->get_q('key');

        if ($key <> md5($aid . "imoreHK"))
            exit("key error");

        $res = $this->Product_application->getApplicationList(0, 0, "", 1, 1, $aid);

        if ($res['result']) {
            $result = $res['result'][0];
            if ($result['application_status'] <> 7) {
                exit("審核狀態不正確");
            } else {
                global $site_global_config;
                $global_url = $site_global_config['URL'];
                $pid = $result['oid'];
                $data = $this->Product->getProductById($pid);
                $data['_photo_url'] = PhotoResize($data['cover'], 180, 180);
                //體驗天數
                $data['_diff_day'] = (int) ((strtotime($data['report_endtime']) - strtotime($data['apply_starttime'])) / 86400);
                //right 產品屬性info
                $attr = array();
                if (!empty($data['price_trial'])) {
                    $data['_attr']['價格'] = $data['price_trial'];
                }
                if (!empty($data['capacity_trial'])) {
                    $data['_attr']['容量'] = $data['capacity_trial'];
                }
                for ($i = 1; $i < 9; $i++) {
                    if (!empty($data['attribute_value' . $i])) {
                        $data['_attr'][$data['attribute_label' . $i]] = $data['attribute_value' . $i];
                    }
                }

                global $site_global_config;
                $root = $site_global_config['WWW'];
                $bt_url = $root . '/product.php?action=report_show&pid=' . $pid . '&aid=' . $aid;

                $mtxt = $data['member_type'] == 5 ? '體驗' : '試用';
                $this->tmpl_assign('mtxt', $mtxt);
                $this->tmpl_assign('bt_url', $bt_url);
                $this->tmpl_assign('data', $data);
                $pageValue['title'] = $data['name'] . " - " . $data['cname'] . " - ";
                $this->tmpl_assign('pageValue', $pageValue);
                $this->tmpl_assign('global_url', $global_url);

                $emailbody = $this->load_tmpl("p_report_show_email.php");
                $url = $global_url . 'product.php?action=report_show&pid=' . $pid . '&aid=' . $aid;
                $subject = "ITrial 確認試用申請";
                $content = $result['username'] . "您好,如果不能看到圖片，請點擊以下url查看 <a href='" . $url . "'>" . $url . "</a>。
			<br><br><br>
		" . $emailbody;
                $receiver = $result['email'];
                $sender = "itrial@nmg.com.hk";

                sendMail($receiver, $sender, $subject, $content);
                echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />email發送成功";
            }
        } else {
            exit("id出錯");
        }
    }

}

$webapp = new Product();
$webapp->run();
?>